package com.tanhua.sso.service;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.sso.mapper.UserMapper;
import com.tanhua.sso.pojo.User;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j //会自动生成一个log对象
public class UserService {


    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    public String login(String phone, String verificationCode) {

        String redisKey ="CHECK_CODE_"+phone;
        //新用户标记 默认为false
        boolean isNew =false;

        //判断验证码是否正确
        String code = redisTemplate.opsForValue().get(redisKey);
        if(!verificationCode.equals(code)){
            return null;//验证码不正确
        }

        //验证成功立即删除验证码
        redisTemplate.delete(redisKey);

        //判断手机号是否为首次登陆
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("mobile",phone);
        User user = userMapper.selectOne(query);

        if (user==null){
            //为空表明为新用户 需要注册
            isNew = true;

            //user = new User();
            // newUser.setId();
            user.setMobile(phone);
            //设置密码 并加密
            user.setPassword(DigestUtils.md5Hex("123456"));

            //注册 插入数据库中
            this.userMapper.insert(user);
        }


        //生成token
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("id", user.getId());


        // 生成token
        String token = Jwts.builder()
                .setClaims(claims) //payload，存放数据的位置，不能放置敏感数据，如：密码等
                .signWith(SignatureAlgorithm.HS256, secret) //设置加密方法和加密盐
                .setExpiration(new DateTime().plusHours(12).toDate()) //设置过期时间，12小时后过期
                .compact();

        //发送mq消息

        try {
            Map<String,Object> msg = new HashMap<>(2);
            msg.put("id",user.getId());
            msg.put("date",System.currentTimeMillis());

            rocketMQTemplate.convertAndSend("tanhua-sso-login",msg);
        } catch (MessagingException e) {

            log.error("发送消息失败",e);

        }

        return token+"|"+isNew;
    }
}
